// pages/search/search.js
let idList = []
let page = 0
let saveKeyword = ''
let count
Page({

  /**
   * 页面的初始数据
   */
  data: {
    musiclist: [],
    top:[],
    isHidden: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.cloud.callFunction({
      name: 'getSearch',
      data:{
        $url: 'toplist'
      }
    }).then((res) =>{
      this.setData({
        top: res.result.list.slice(0,4)
      })
    })
  },
  change(event){
    if(!event.detail) {
      wx.removeStorageSync('musiclist')
      this.setData({
        isHidden: false,
        musiclist: []
      })
    }
  },
  search(event) {
    this.setData({
      isHidden: true
    })
    let keyword
    if(event){
      wx.removeStorageSync('musiclist')
      this.setData({
        musiclist: []
      })
      keyword = event.detail
      saveKeyword = keyword
    } else{
      keyword = saveKeyword
    }
    wx.showToast({
      title: '正在搜索中',
      icon:'loading',
      mask: 'true',
      duration: 10000
    })
    this.getSearchlist(keyword)
  },
  getSearchlist(keyword){
    wx.cloud.callFunction({
      name: 'search',
      data: {
        keyword,
        page
      }
    }).then( res => {
      let songs = res.result.result.songs
      count = res.result.result.songCount
      let idList = []
      if(songs){
        songs.map((item) => {
          idList.push(item.id)
        })
        this.getMusiclist(idList)
        idList = []
      } else{
       wx.hideToast()
       wx.showToast({
         title: '暂无搜索内容~',
         icon: 'none'
       }) 
      }
    })
  },
  getMusiclist(idList) {
    wx.cloud.callFunction({
      name: 'music',
      data: {
        $url: 'musicDetail',
        musicIdList: idList
      }
    }).then((res) => {
      this.setData({
        musiclist: this.data.musiclist.concat(res.result) 
      })
      wx.setStorageSync('musiclist', this.data.musiclist)
      wx.hideToast()
    })
  },
  onClick(event){
    const index = event.currentTarget.dataset.index
    wx.navigateTo({
      url: `/pages/toplist/toplist?index=${index}`
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.isHidden){
      page++
      if(page * 15 > count){
        wx.showToast({
          title: '没有更多啦~',
          icon: 'none'
        })
        return
      } else{
        this.search()
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})